package com.example.studydemo.hmosnote;

import com.google.gson.Gson;
import ohos.aafwk.ability.Ability;
import ohos.aafwk.content.Intent;
import ohos.agp.components.Component;
import ohos.agp.components.Text;
import ohos.agp.components.Image;
import ohos.agp.components.TextField;
import ohos.agp.utils.TextTool;
import ohos.sysappcomponents.contact.entity.Note;

import java.text.SimpleDateFormat;
import java.util.Date;

public class WriteNoteAbility extends Ability {
    private NoteBean noteBean;

    @Override
    protected void onStart(Intent intent) {
        super.onStart(intent);
        setUIContent(ResourceTable.Layout_ability_write_note);
        String note = intent.getStringParam("note");
        if (!TextTool.isNullOrEmpty(note)) {
            noteBean = new Gson().fromJson(note, NoteBean.class);
        }
        Text tvTiltle = (Text) findComponentById(ResourceTable.Id_tv_title);
        tvTiltle.setText(noteBean == null ? "创建" : "编辑");
        Image ivBack = (Image) findComponentById(ResourceTable.Id_iv_back);
        Image ivRight = (Image) findComponentById(ResourceTable.Id_iv_right);
        TextField tfTitle = (TextField) findComponentById(ResourceTable.Id_tf_title);
        TextField tfContent = (TextField) findComponentById(ResourceTable.Id_tf_content);
        ivBack.setVisibility(Component.VISIBLE);
        ivRight.setVisibility(Component.VISIBLE);
        ivBack.setClickedListener(component -> {
            terminateAbility();
        });
        ivRight.setClickedListener(component -> {
            if (noteBean == null) {
                noteBean = new NoteBean();
                noteBean.setTitle(tfTitle.getText());
                noteBean.setContent(tfContent.getText());
                String time = new SimpleDateFormat("yyyy-MM-dd HH:mm").format(new Date());
                noteBean.setAddTime(time);
                noteBean.setUpdateTime(time);
                DBUtils.getInstance(this).insert(noteBean);
                terminateAbility();
            } else {
                noteBean.setTitle(tfTitle.getText());
                noteBean.setContent(tfContent.getText());
                String time = new SimpleDateFormat("yyyy-MM-dd HH:mm").format(new Date());
                noteBean.setUpdateTime(time);
                DBUtils.getInstance(this).update(noteBean);
            }
        });
        if (note != null) {
            tfTitle.setText(noteBean.getTitle());
            tfContent.setText(noteBean.getContent());
        }
    }
}
